'''
数据库相关的操作
'''

import pymysql


def connect(db_info: dict):
    '''
    连接数据库
    :param db_info: 字典格式的，数据库相关的信息
                    {"host":"192.168.0.103","port":3306,"user":"root","pwd":"123456","dbname":"apple"}
    :return: 连接对象
    '''


    try:
        conn = pymysql.connect(user=db_info['user'],
                               password=db_info['pwd'] ,
                               host=db_info['host'],
                               database=db_info['dbname'],
                               port=db_info['port'],
                               charset="utf8")
        print("连接数据库成功")
        return conn
    except Exception as e:
        print(f"连接数据库异常，异常信息为：{e}")

def disconnect(conn):
    '''
    断开连接
    :param conn: 连接对象
    :return:
    '''
    try:
        conn.close()
    except Exception as e:
        print(f"断开数据库连接连接异常，异常信息为：{e}")

#  执行sql语句
def execute(conn,sql):
    try:
        c = conn.cursor() # 获取游标，类似atestatement
        c.execute(sql) # 使用游标执行sql语句
        conn.commit() #  提交
        print(f"执行{sql}成功")
    except Exception as e:
        print(f"执行{sql}异常，异常信息为：{e}")

def delete_user(db_info,phone):
    '''
    根据手机号删除用户
    :param db_info:
    :param phone:
    :return:
    '''
    conn = connect(db_info)
    execute(conn, f"delete from member where mobilephone={phone}")
    disconnect(conn)

if __name__ == '__main__':
    db_info= {"host":"192.168.0.103","port":3306,"user":"root","pwd":"123456","dbname":"apple"}
    # conn=connect(db_info)
    # execute(conn,"delete from member where mobilephone=18736478987")
    # disconnect(conn)

    delete_user(db_info, "13056989230")